package net.dopan.pigframe.auth.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dopan.pigframe.core.base.controller.response.ResponseBean;
import net.dopan.pigframe.core.utils.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Package: net.dopan.pigframe.auth.controller
 * @Title: AuthenticationController
 * @Description: 认证、登出
 * @author: 刘宽
 * @date: 2018/9/6 17:11
 */
@RestController
@RequestMapping("/authentication")
@Api(tags = "认证、登出接口", description = "认证、登出")
public class AuthenticationController {

    @Autowired
    @Qualifier("consumerTokenServices")
    private ConsumerTokenServices consumerTokenServices;

    /**
     * 用户信息校验
     * @param authentication 信息
     * @return 用户信息
     */
    @RequestMapping("/user")
    @ApiOperation(value = "认证", notes = "用户信息校验")
    public Object user(Authentication authentication) {
        return authentication.getPrincipal();
    }

    /**
     * 清除Redis中 accesstoken refreshtoken
     *
     * @param accesstoken  accesstoken
     * @return true/false
     */
    @DeleteMapping("/removeToken")
    @ApiOperation(value = "登出", notes = "清除Redis中 accesstoken refreshtoken")
    @CacheEvict(value = SecurityConstants.TOKEN_USER_DETAIL, key = "#accesstoken")
    public ResponseBean removeToken(String accesstoken) {
        if (consumerTokenServices.revokeToken(accesstoken)) {
            return new ResponseBean(ResponseBean.SUCCESS, "注销成功", null);
        } else {
            return new ResponseBean(ResponseBean.FAIL, "注销失败", null);
        }
    }
}